package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    private static final Logger log = LoggerFactory.getLogger(CategoryServiceImpl.class);
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Override
    public PageResult pageList(CategoryPageQueryDTO categoryPageQueryDTO) {
        log.info("分页查询参数:{}",categoryPageQueryDTO);
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        List<Category> list = categoryMapper.pageList(categoryPageQueryDTO);
        Page< Category> page = (Page< Category>) list;
        return new PageResult(page.getTotal(),page.getResult());

    }

    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    @Override
    public void save(Category category) {
        category.setSort(StatusConstant.DISABLE);
        categoryMapper.insert(category);
    }

    @Override
    public void deleteById(Long id) {
        Dish dish = new Dish();
        dish.setCategoryId(id);
        List<Dish> dishResult = dishMapper.select(dish);
        log.info("service:查询菜品:{}",dishResult);
        if (dishResult.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);

        }else{

            categoryMapper.deleteById(id);
        }
    }

    @Override
    public List<Category> getTypelist(Integer type) {
        List<Category> list=categoryMapper.selectByType(type);
        return list;
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Category category = new Category();
        category.setStatus(status);
        category.setId(id);
        categoryMapper.update(category);
    }
}
